package com.news.servlet.admin;

import com.news.model.News;
import com.news.model.Sort;
import com.news.model.User;
import com.news.service.NewsService;
import com.news.service.impl.NewsServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@WebServlet("/admin/newsAdd")
public class NewsAddServlet extends HttpServlet {
    private NewsService newsService = new NewsServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 获取所有分类列表（从sort_id为2开始）
            List<Sort> sortList = newsService.getAllSorts().stream()
                    .filter(sort -> sort.getSort_id() >= 2)
                    .collect(Collectors.toList());
            request.setAttribute("sortList", sortList);
            request.getRequestDispatcher("/admin/news_add.jsp").forward(request, response);
        } catch (Exception e) {
            request.getSession().setAttribute("message", "获取分类列表失败：" + e.getMessage());
            response.sendRedirect(request.getContextPath() + "/admin/newsManage");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 检查是否是多部分请求
            if (!ServletFileUpload.isMultipartContent(request)) {
                throw new ServletException("表单必须包含文件上传字段");
            }

            // 创建文件上传处理器
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            
            // 解析请求
            List<FileItem> items = upload.parseRequest(request);
            
            // 创建新闻对象
            News news = new News();
            String imagePath = null;
            
            // 处理表单字段
            for (FileItem item : items) {
                if (item.isFormField()) {
                    // 处理普通表单字段
                    String fieldName = item.getFieldName();
                    String value = item.getString("UTF-8");
                    
                    switch (fieldName) {
                        case "title":
                            news.setTitle(value);
                            break;
                        case "sort_id":
                            news.setSort_id(Integer.parseInt(value));
                            break;
                        case "content":
                            news.setContent(value);
                            break;
                    }
                } else {
                    // 处理文件上传
                    if (item.getSize() > 0) {
                        String fileName = System.currentTimeMillis() + "_" + 
                            item.getName().substring(item.getName().lastIndexOf("/") + 1);
                        String uploadPath = getServletContext().getRealPath("/images");
                        File uploadDir = new File(uploadPath);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdir();
                        }
                        File file = new File(uploadPath, fileName);
                        item.write(file);
                        imagePath = fileName;
                    }
                }
            }
            
            // 设置作者（从session获取当前用户）
            User user = (User) request.getSession().getAttribute("user");
            news.setWriter(user.getUsername());
            
            // 保存新闻
            if (newsService.addNews(news, imagePath)) {
                request.getSession().setAttribute("message", "新闻添加成功！");
                response.sendRedirect(request.getContextPath() + "/admin/newsManage");
            } else {
                request.getSession().setAttribute("message", "新闻添加失败！");
                response.sendRedirect(request.getContextPath() + "/admin/news_add.jsp");
            }
        } catch (Exception e) {
            request.getSession().setAttribute("message", "新闻添加失败：" + e.getMessage());
            response.sendRedirect(request.getContextPath() + "/admin/news_add.jsp");
        }
    }
} 